import {defineStore} from 'pinia'
import {ref} from 'vue'
import {loginAPI} from '@/apis/user.js'
import {useCartStore} from '@/stores/cartStore.js'
import {mergeCartAPI} from '@/apis/cart.js'

// 存放用户相关的数据
export const useUserStore = defineStore('user', () => {
	const cartStore = useCartStore()

	// state
	const userInfo = ref({})
	// action
	const getUserInfo = async ({account, password}) => {
		const res = await loginAPI({account, password})
		userInfo.value = res.result
		// 登录时合并本地购物车数据至接口购物车
		await mergeCartAPI(cartStore.cartList.map(item => {
			return {
				skuId: item.skuId,
				selected: item.selected,
				count: item.count
			}
		}))
		cartStore.updateCartList()
	}

	const clearUserInfo = () => {
		// 清空用户个人信息数据
		userInfo.value = {}
		// 清空购物车列表数据
		cartStore.clearCart()
	}

	return {
		userInfo,
		getUserInfo,
		clearUserInfo
	}
}, {
	persist: true
})
